package com.invengo.module_robot.ui.activity;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.NavInflater;
import androidx.navigation.Navigation;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.invengo.base.router.RouterActivityPath;
import com.invengo.library_orionstar.PathBean;
import com.invengo.library_orionstar.SkillApiHelper;
import com.invengo.module_robot.BR;
import com.invengo.module_robot.R;
import com.invengo.module_robot.databinding.ActivityRobotBinding;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.KLog;

/**
 * @author buoker
 * @version 1.0.0
 * @date 2024/03/20
 * @className java.lang.String
 */
@Route(path = RouterActivityPath.Robot.ROBOT_MAIN)
public class RobotActivity extends BaseActivity<ActivityRobotBinding, RobotViewModel> {
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_robot;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onStart() {
        super.onStart();
        SkillApiHelper.startApp();
    }

    @Override
    protected void onResume() {
        super.onResume();
        SkillApiHelper.moveToForeground();
    }

    @Override
    protected void onPause() {
        super.onPause();
        SkillApiHelper.moveToBack();
    }

    @Override
    protected void onStop() {
        super.onStop();
        SkillApiHelper.destroyApp();
    }

    String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    @Override
    public void initNavgation() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission.requestEach(permissions)
                .subscribe(permission -> {
                    if (permission.granted) {
                        // 用户已经同意该权限
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        System.exit(0);
                    } else {
                        System.exit(0);
                    }
                });
        String path = getPath();
        if (TextUtils.isEmpty(path)) {
            path = "/robot/Search";
        }
        NavController navController = Navigation.findNavController(this, R.id.main_fragmentcontainerview);
        NavInflater navInflater = navController.getNavInflater();
        NavGraph navGraph = navInflater.inflate(R.navigation.navigation_robot);
        navGraph.setStartDestination(getNavigationId(path));
        navController.setGraph(navGraph, null);
    }

    private String getPath() {
        String path = "";
        try {
            if (getIntent().getExtras() != null) {
                String extras = (String) getIntent().getExtras().get("params");
                List<PathBean> beans = new Gson().fromJson(extras, new TypeToken<List<PathBean>>() {
                }.getType());
                if (beans != null && !TextUtils.isEmpty(beans.get(0).getValue()))
                    if (!TextUtils.isEmpty(beans.get(0).getValue())) {
                        path = beans.get(0).getValue();
                    }
            } else {
                KLog.e("什么跳转数据都没有");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }


    /**
     * 获取导航id
     *
     * @param path 路径
     * @return int
     */
    private int getNavigationId(String path) {
        int startId = R.id.searchFragment;
        switch (path) {
            case RouterActivityPath.Robot.ROBOT_SEARCH:
                startId = R.id.searchFragment;
                break;
            case RouterActivityPath.Robot.ROBOT_ADVERT:
                startId = R.id.advertFragment;
                break;
            case RouterActivityPath.Robot.ROBOT_POPULAR:
                startId = R.id.popularFragment;
                break;
        }
        return startId;
    }

    /**
     * 初始视图可观察
     */
    @Override
    public void initViewObservable() {
        viewModel.ui.launchEvent.observe(this, s -> {
            new Handler().postDelayed(() -> {
                Navigation.findNavController(RobotActivity.this, R.id.main_fragmentcontainerview).navigate(getNavigationId(s));
            }, 1500);
        });
        viewModel.ui.backEvent.observe(this, s -> {
            onBackPressed();
        });
    }
}
